<template>
  <el-dialog :visible.sync="showInfo" width="920px" top="10vh" :close-on-click-modal='false'
    :close-on-press-escape='false' @close="dialogClose">
    <h2 slot="title" class="tx-c">项目详情</h2>
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="基本信息" name="1">
        <el-form autocomplete="off" label-width="125px" :model="info" class="form_flex">
          <el-form-item v-for="(v, i) in headerList" :key="i" :label="v.label+'：'" class="mr8">
            <div v-if="v.prop === 'departments_id'" class="block_cell">{{info.department?info.department.name:'无'}}
            </div>
            <div v-else-if="v.prop === 'leader_id'" class="block_cell">{{info.leader_info?info.leader_info.name:'无'}}
            </div>
            <div v-else-if="v.prop === 'complete_id'" class="block_cell">{{objToStr(info.complete_name)||'无'}}
            </div>
            <div v-else-if="v.prop === 'review_status'" class="block_cell">{{info.status}}<span
                v-if="info.review.review_comment">：{{info.review.review_comment}}</span> </div>
            <div v-else-if="v.prop === 'disciplines_id'" class="block_cell">{{info.discipline?info.discipline.name:'无'}}
            </div>
            <div v-else-if="v.prop === 'leader_type'" class="block_cell">{{firstTypeObj[info.leader_type] || '无'}}</div>
            <div v-else-if="v.prop === 'project_level'" class="block_cell">
              {{projectLevelObj[info.project_level] || '无'}}</div>
            <div v-else-if="v.prop === 'project_funds' || v.prop === 'funds1'" class="block_cell">{{info[v.prop]}}万元
            </div>
            <div v-else class="block_cell">{{info[v.prop] || '无'}}</div>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="文件" name="2">
        <div class="pl16">
          <div v-for="(v,i) in upfilesObj" :key="'label' + v">
            <h3 class="mb8 f-18">{{v}}：</h3>
            <div v-if="files[i.trim()] && files[i.trim()].length > 0" class="mb16">
              <div class="pl16">
                <el-image :z-index='3000' v-for="item in echoFiles(files[i.trim()],true)" :key='item.id'
                  class="details_image" :src="uploadUrl + item.file_path"
                  :preview-src-list="srcList(echoFiles(files[i.trim()],true))">
                </el-image>
              </div>
              <div class="mt8">
                <p class="inspectionFile" v-for="v in echoFiles(files[i.trim()],false)" :key='"file" + v.id'>
                  <span class="shou f-16 c-black" @click="uploadFiles(v.file_path,v.file_name)"><i
                      class="iconfont icon-ziyuan"></i>{{v.file_name}}</span>
                </p>
                <p v-if="i == '5 '" class="mb16 pl16">
                  <el-button type="primary" size="small" plain @click="upload(i)">上传文件</el-button>
                </p>
              </div>
            </div>
            <div v-else>
              <p v-if="isUpload(i) || i == '5 '" class="mb16 pl16">
                <el-button type="primary" size="small" plain @click="upload(i)">上传文件</el-button>
              </p>
              <p v-else class="mb16 c-9 pl16 f-16">暂无文件</p>
            </div>
          </div>
          <input type="file" accept="image/*,.xlsx,.xls,.doc,.docx,.ppt,.pptx,.pdf,.txt" ref="file" @change="fileChange"
            style="display:none">
        </div>
      </el-tab-pane>
      <el-tab-pane label="项目经费" name="3">
        <el-button :loading='btnLoading' class="button" @click="printTable" size="medium">打印</el-button>
        <el-table ref="table" border highlight-current-row v-loading="tableLoading" stripe height='500px'
          :data="tableData" @sort-change="tableSortChange" style="width: 601px">
          <el-table-column align="center" prop="time" label="时间" width="200" sortable="custom">
          </el-table-column>
          <el-table-column align="center" prop="amount" label="金额(万元)" width="200" sortable="custom">
          </el-table-column>
          <el-table-column align="center" prop="type" label="类型" width="200" sortable="custom">
          </el-table-column>
        </el-table>
        <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
      </el-tab-pane>
      <el-tab-pane label="审核记录" name="4">
        <div class="pl16 timeline_content" v-loading='timelineLoading'>
          <el-timeline :reverse="false">
            <el-timeline-item class="f-16" v-for="(activity, index) in activities" :key="index"
              :color="index === 0 ? '#1ECA66' : ''" :timestamp="activity.timestamp">
              {{activity.content}}
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script>
  import {
    headerList
  } from '../js/portrait'
  import {projectLevelObj,firstTypeObj} from '@/assets/js'
  import {
    ApiupLoadFiles,
    ApiprojectsFunds,
    ApiprojectsReviewRecord,
    ApiprojectsUploadFile
  } from '@/api'
  import {isIMage} from "@/utils/test";
  import {objToStr} from "@/utils/index";
  import {uploadUrl} from '@/api/request'
  import print from 'print-js'
  export default {
    props: {
      info: {
        default: () => ({
          review: {}
        })
      }
    },
    computed: {
      files() {
        return this.info.files || {
          1: [],
          2: [],
          3: [],
          4: [],
          5: [],
          6: [],
          7: [],
          8: [],
          9: []
        }
      },
    },
    data() {
      return {
        objToStr,
        uploadUrl: uploadUrl(),
        headerList,
        projectLevelObj,
        firstTypeObj,
        showInfo: false,
        upfilesObj: {
          '1 ': '项目申报书',
          '10 ': "项目立项通知书",
          '2 ': '项目批准通知书',
          '3 ': '项目计划书',
          '4 ': '项目计划书批复件',
          '5 ': '年度报告',
          '6 ': '中期检查报告',
          '7 ': '结题报告',
          '8 ': '结题证明',
          '9 ': '验收报告'
        },
        pageparm: {
          page: 1,
          perPage: 10,
          total: null,
          sort_str: null,
          sort_order: 'desc',
        },
        activeName: '1',
        tableData: [],
        tableLoading: false,
        btnLoading: false,
        activities: [],
        timelineLoading: false,

        type: null, //文件上传类型
      }
    },
    methods: {
      upload(i) {
        this.type = i.trim()
        this.$refs.file.click()
      },
      fileChange(e) {
        const loading = this.$loading({
          lock: true,
          text: '上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        const formData = new FormData()
        const file = e.target.files[0]
        formData.append('file', file)
        formData.append('project_id', this.info.id)
        formData.append('type', this.type)
        ApiprojectsUploadFile(formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
          const obj = {
            file_path: res.data[0],
            file_name: file.name
          }
          if (this.info.files[this.type]) {
            this.info.files[this.type].push(obj)
          } else {
            this.info.files[this.type] = [{
              file_path: 123,
              file_name: 456
            }]
            this.info.files[this.type] = [obj]
          }
          this.$parent.getList()
          this.$forceUpdate();
          this.$message.success('文件上传成功！')
        }).finally(() => {
          loading.close()
        })
      },
      isUpload(i) {
        return ["2 ", "3 ", "4 "].includes(i)
      },
      tableSortChange(column) {
        if (column.order === "descending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "desc";
        } else if (column.order === "ascending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "asc";
        } else {
          this.pageparm.sort_str = null;
          this.pageparm.sort_order = null;
        }
        this.getList()
      },
      callFather(pageparm) {
        this.pageparm.page = pageparm.page
        this.pageparm.perPage = pageparm.perPage
        this.getList()
      },
      printTable() {
        this.btnLoading = true
        const name = this.info.name;
        const department_name = this.info.department.name;
        ApiprojectsFunds({
          allPage: 2
        }, this.info.id).then(({
          data,
          page
        }) => {
          print({
            printable: data,
            properties: [{
                field: 'time',
                displayName: '时间'
              },
              {
                field: 'amount',
                displayName: '金额（万元）'
              },
              {
                field: 'type',
                displayName: '类型'
              }
            ],
            type: 'json',
            gridHeaderStyle: 'border: 1px solid #909399;', //表格头样式
            gridStyle: 'border: 1px solid #909399; text-align:center;', // 表格体样式
            header: `<div> <div class="title">${name}</div> <div>科室：${department_name}</div> </div>`,
            style: '.title {text-align:center;font-weight: 600;};'
          })
        }).catch(() => {
          this.$message.error('获取数据失败！')
        }).finally(() => {
          this.btnLoading = false
        })

      },
      getList() {
        this.tableLoading = true
        ApiprojectsFunds(this.pageparm, this.info.id).then(({
          data,
          page
        }) => {
          this.tableData = data
          this.pageparm.total = page.total
        }).finally(() => {
          this.tableLoading = false
        })
      },
      handleClick() {
        if (this.activeName === '3') {
          this.getList()
        } else if (this.activeName === '4') {
          this.timelineLoading = true
          this.activities = []
          ApiprojectsReviewRecord(this.info.id).then(({
            data
          }) => {
            this.activities = data
          }).finally(() => {
            this.timelineLoading = false
          })
        }
      },
      dialogClose() {
        this.activeName = '1'
      },
      echoFiles(arr = [], flag = true) {
        return arr.filter(item => isIMage(item.file_name) === flag)
      },
      srcList(arr = []) {
        return arr.map(item => this.uploadUrl + item.file_path)
      },
      uploadFiles(url, name) {
        ApiupLoadFiles(url).then(res => {
          let a = document.createElement("a")
          a.href = URL.createObjectURL(res)
          a.download = name
          a.click()
          URL.revokeObjectURL(a.href)
        })
      },
    }
  }
</script>
<style lang='less' scoped>
  .button {
    margin-bottom: 4px;
  }

  .timeline_content {
    height: 600px;
    overflow-y: auto;
  }

  /deep/.el-timeline {
    padding-top: 2px;
  }

  /deep/.el-timeline-item__content {
    line-height: 20px;
  }
</style>